<template>
    <div class="container_box">
        <div class="main_box">
            <div class="verbal_trick">
                <el-scrollbar class="scrollbar_left">
                    <el-form ref="ruleFormRef" :model="formData" label-width="auto" class="form" :rules="rules">
                        <el-form-item label="标题" prop="title">
                            <el-input
                                v-model="formData.title"
                                placeholder="请输入标题名称"
                                style="width: 598px"
                                show-word-limit
                                maxlength="15" />
                        </el-form-item>
                        <el-form-item label="分组">
                            <el-cascader
                                ref="cascaderRef"
                                v-model="formData.group_id"
                                style="width: 598px"
                                :props="defaultProps1"
                                :options="groupOptions"
                                @change="orgChange" />
                        </el-form-item>
                        <el-form-item label="描述">
                            <el-input
                                v-model="formData.desc"
                                style="width: 598px"
                                placeholder="请输入描述"
                                type="textarea"
                                show-word-limit
                                maxlength="50" />
                        </el-form-item>
                        <el-form-item label="话术内容" prop="group_id">
                            <div class="content">
                                <div class="content-left">
                                    <MaterialContent
                                        ref="materialContentRef"
                                        :max-num="9"
                                        input-disabled
                                        :single-list="[0]"
                                        placeholder="请选择文本"
                                        :input-content-tabs="inputContentTabs"
                                        :show-material-tabs="showMaterialTabs"
                                        :input-content-data="inputContentData"
                                        :material-content-data="materialContentData"
                                        @change="changeMaterial"
                                        @changeTextIdList="changeTextIdList" />
                                </div>
                            </div>
                        </el-form-item>
                    </el-form>
                </el-scrollbar>
                <div class="border_lin"></div>
                <el-scrollbar class="scrollbar_right">
                    <div class="content-right">
                        <div class="phone-title">欢迎语预览</div>
                        <PhonePreview ref="phonePreviewRef" />
                    </div>
                </el-scrollbar>
            </div>

            <ZWMatericalLib ref="ZWMatericalLibRef" @submit="getMaterlib" />
        </div>
        <div class="footer_box">
            <el-button @click="$e => cancelAdd()"> 取消 </el-button>
            <el-button type="primary" @click="save(ruleFormRef)"> 保存 </el-button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onBeforeMount, watch } from 'vue';
import { useStore } from '@/store';
import router from '@/router';
import { useRoute } from 'vue-router';
import { groupData, create, edit, preview } from '@/api/highMaterial/verbalTrick';
import ZWMatericalLib from './components/ZWMatericalLib.vue';
import Friend from '../Friend.vue';
import ZWEmoji from '@/components/ZWEmoji.vue';

import { getSetionId, IsNotEmpty, getSuffixIcon } from '@/utils/utils';

import { ElMessage } from 'element-plus';

import { initMaterialData } from '@/utils/utils';
import MaterialContent from '@/components/zw/materialContent/index.vue';
import PhonePreview from '@/components/zw/phonePreview/welcomePhonePreview/materialPreview/index.vue';

const inputContentTabs = ref<Array<number>>([1]); // 配置欢迎语输入框选项
const showMaterialTabs = ref<Array<string>>(['1', '2', '5', '3']); // 配置选择素材组件类型
const inputContentData = ref<string>(''); //  用户存放回显数据  欢迎语输入框
const materialContentData = ref<Array<any>>([]); //  用户存放回显数据  欢迎语素材

const materialResult = ref<any>(null);
const cascaderRef: any = ref(null); // 选择分组ref
const text_ids = reactive<Array<any>>([]);

const store = useStore();
const route = useRoute();
const ruleFormRef = ref(null);
const ZWMatericalLibRef = ref(null);
const type = ref(route.query.type);
const pageId = ref(route.query.id);
const groupType = ref(route.query.groupType);
const speechcraft_type = ref(route.query.seepType);

const fileList = ref([]);
const fileList2 = ref([]);
const newArr = ref([]);
const emojiVisible = ref(false);

const groupOptions = ref([]);
const defaultProps1 = {
    checkStrictly: true, // 是否严格的遵守父子节点不互相关联
    emitPath: false,
    multiple: false,
    label: 'name',
    value: 'id'
};
const rules = reactive({
    title: [
        {
            required: true,
            message: '请输入标题名称',
            trigger: 'blur'
        }
    ],
    group_id: [
        {
            required: true,
            message: '请选择话术内容！',
            trigger: 'blur'
        }
    ]
});
const uploadList = reactive([
    { id: '2', icon: '/static/file/pic.png', name: '图片' },
    { id: '4', icon: '/static/file/mov.png', name: '视频' },
    { id: '5', icon: '/static/file/ysb.png', name: '文件' },
    { id: '6', icon: '/static/file/link.png', name: '链接' }
]);
// from 表单收集的数据
const formData = ref({
    title: '',
    group_id: Number(route.query.group_id), // 是否设置欢迎语
    content_id: '',
    desc: '',
    content: '', // 欢迎语文本
    speechcraft_type: speechcraft_type.value,
    welcome_info: {
        welcome_material: [],
        welcome_text: ''
    }
});

const changeMaterial = (val: any) => {
    materialResult.value = val;
};

const changeTextIdList = (res: any[]) => {
    !!res.length && text_ids.splice(0, text_ids.length, ...res);
};

// 插入名字
const insetName = () => {
    if (formData.value.content.length >= 1000) {
        ElMessage.warning('字数已经超过规定最大字数');
        return;
    }
    formData.value.content += '##客户姓名##';
    fileList.value[0] = {
        type: 1,
        content: formData.value.content
    };
};
//更改欢迎语
const changeWords = () => {
    if (formData.value.content.length > 1000) {
        ElMessage.warning('字数已经超过规定最大字数');
        return;
    }
    fileList.value[0] = {
        type: 1,
        content: formData.value.content
    };
};
//打开上传文件弹框
const openUpload = (num: string) => {
    ZWMatericalLibRef.value.materVisible = true;
    ZWMatericalLibRef.value.baseId = num; //打开对应的基础素材
    ZWMatericalLibRef.value.existFile = Number(9 - fileList2.value.length); //打开对应的基础素材
};
//表情包管理
const chooseEmoji = (emoji: any) => {
    if (formData.value.content.length >= 1000) {
        ElMessage.warning('字数已经超过规定最大字数');
        return;
    }
    //事件。数据包含文本区域的值
    formData.value.content = formData.value.content + emoji;
    emojiVisible.value = false;
    fileList.value[0] = {
        type: 1,
        content: formData.value.content
    };
};
// 清空文本
const clearText = () => {
    formData.value.content = '';
    formData.value.content_id = '';
    const index = fileList.value.findIndex((i: any) => i.type == 1);
    if (index != -1) {
        fileList.value.splice(index, 1);
    }
};
// 获取选择的信息
const getMaterlib = (res: any) => {
    // 文本
    if (res.type == 1) {
        formData.value.content_id = res.data[0].id;
        if (formData.value.content.length >= 1000) {
            ElMessage.warning('字数已经超过规定最大字数');
            return;
        }
        if (formData.value.content !== '##客户姓名##') {
            formData.value.content = '';
            res.data.map((item: any) => {
                formData.value.content = item.content;
            });
        } else {
            res.data.map((item: any) => {
                formData.value.content += item.content;
            });
        }

        fileList.value[0] = {
            type: 1,
            content: formData.value.content
        };
    } else {
        const result = [];
        if (res.data.length > 0) {
            res.data.forEach((item: any) => {
                item.type = res.type;
                result.push(item);
            });
        }
        if (res.local) {
            fileList.value = fileList.value.concat(changeLocalType(result));
        } else {
            fileList.value = fileList.value.concat(changeType(result));
        }
    }
    newArr.value = fileList.value.filter((item: any) => {
        return item.type != 1;
    });
};
const changeLocalType = (data: any[]) => {
    const result = [];
    if (data.length > 0) {
        data.forEach((item: any) => {
            // 图片
            if (item.type == 2) {
                item.cur_icon = '/static/file/pic.png';
                item.title = item.name;
                item.absolute_url = item.url;
                item.type2 = 1;
            }
            ///视频
            if (item.type == 4) {
                item.cur_icon = '/static/file/mov.png';
                item.title = item.name;
                item.type2 = 2;
            }
            // 音频
            if (item.type == 3) {
                item.cur_icon = '/static/file/mp3.png';
                item.title = item.name;
                item.type2 = 4;
            }
            // 链接
            if (item.type == 6) {
                item.cur_icon = '/static/file/link.png';
                item.name = item.title;
                item.type2 = 3;
            }
            // 文件
            if (item.type == 5) {
                item.cur_icon = getSuffixIcon(item.url);
                item.title = item.name;
                item.type2 = 5;
            }
            item.is_local = true;
            result.push(item);
        });
    }
    return result;
};
// 转换选中信息
const changeType = (data: any[]) => {
    const result = [];
    if (data.length > 0) {
        data.forEach((item: any) => {
            // 图片
            if (item.type == 2) {
                item.cur_icon = '/static/file/pic.png';
                item.name = item.file_name;
                item.type2 = 1;
            }
            ///视频
            if (item.type == 4) {
                item.cur_icon = '/static/file/mov.png';
                item.name = item.file_name;
                item.type2 = 2;
            }
            // 音频
            if (item.type == 3) {
                item.cur_icon = '/static/file/mp3.png';
                item.name = item.file_name;
                item.type2 = 4;
            }
            // 链接
            if (item.type == 6) {
                item.cur_icon = '/static/file/link.png';
                item.name = item.title;
                item.content = item.desc;
                item.type2 = 3;
            }
            // 文件
            if (item.type == 5) {
                item.cur_icon = getSuffixIcon(item.mediaFileInfo?.absolute_url);
                item.name = item.mediaFileInfo?.name;
                item.title = item.mediaFileInfo?.name;
                item.type2 = 5;
            }
            result.push(item);
        });
    }
    return result;
};
// 删除上传的文件
const remove = (data: any) => {
    if (data.code) {
        fileList.value = fileList.value.filter((item: any) => item.code != data.code);
        newArr.value = newArr.value.filter((item: any) => item.code != data.code);
    } else {
        fileList.value = fileList.value.filter((item: any) => item.id != data.id);
        newArr.value = newArr.value.filter((item: any) => item.id != data.id);
    }
    fileList2.value = fileList.value;
};
const cancelAdd = (flag?: boolean) => {
    store.commit('newCode/BACK_ID', speechcraft_type.value);
    // const paramsall = {
    //     group_id: formData.value.group_id,
    //     group_type: speechcraft_type.value
    // };

    const query: any = {
        groupId: route.query.group_id,
        group_type: speechcraft_type.value
    };
    if (flag) {
        query.group_id = formData.value.group_id;
    }

    router.push({ path: '/content/highMaterial/verbalTrick', query });
};
// 欢迎语数据转换
const welDataBase = (data?: any) => {
    data.forEach((item: any) => {
        if (item.fromList) {
            formData.value.speechcraft_attachment_ids.push(item.id);
        } else {
            if (item.type != 1) {
                if (item.is_local) {
                    if (item.type == 6) {
                        formData.value.local_link.push({
                            link_title: item.title,
                            link_url: item.link_url,
                            link_decs: item.link_desc,
                            link_share_image: item.cover_image_url
                        });
                    } else {
                        formData.value.local_content.push({
                            code: item.code,
                            type: item.type2
                        });
                    }
                } else {
                    formData.value.media_content.push({
                        media_content_id: item.fromList ? item.content_id : item.id,
                        type: item.type2
                    });
                }
            }
        }
    });
};
//获取文件类型
const url = (data: any) => {
    const fileTYpe = {
        '.pdf': '/static/file/pdf.png',
        '.doc': '/static/file/doc.png',
        '.docx': '/static/file/doc.png',
        '.xls': '/static/file/xls.png',
        '.xlsx': '/static/file/xls.png',
        '.ppt': '/static/file/ppt.png',
        '.pptx': '/static/file/ppt.png'
    };
    if (data.name.substring) {
        const last = data.name.substring(data.name.lastIndexOf('.'));
        return fileTYpe[last] || '/static/file/file.png';
    }
};
const echoFn = (data: any) => {
    formData.value.title = data.title;
    formData.value.group_id = data.group_id;
    formData.value.desc = data.desc;
    // formData.welcome_info = data.welcome_info
    inputContentData.value = data.welcome_info.welcome_text;
    materialContentData.value = initMaterialData(data.welcome_info.welcome_material);
};
const save = async (formEl: any) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            formData.value.welcome_info = materialResult.value.welcome_info;
            !!text_ids.length && (formData.value['content_id'] = text_ids[text_ids.length - 1]);
            if (formData.value.welcome_info.welcome_text == '') {
                ElMessage.warning('请填写话术内容！');
                return;
            }
            // welDataBase(fileList.value)
            // return
            if (type.value == 'new') {
                create(formData.value).then((res: any) => {
                    ElMessage.success('保存成功！');
                    // return
                    cancelAdd(true);
                    // router.push({ path: '/content/highMaterial/verbalTrick', query: { gpId: '' + speechcraft_type.value } })
                });
            } else {
                formData.value.id = pageId.value;
                edit(formData.value).then((res: any) => {
                    ElMessage.success('保存成功！');
                    cancelAdd(true);
                    // router.push('/content/highMaterial/verbalTrick')
                });
            }
        }
    });
};
const editVerbal = () => {
    if (type.value == 'edit') {
        preview({ speechcraft_id: pageId.value }).then((data: any) => {
            formData.value.speechcraft_attachment_ids = [];
            echoFn(data);
        });
    }
};
// 选择完地区后立即关闭
const orgChange = () => {
    cascaderRef.value.togglePopperVisible();
};

editVerbal();
onBeforeMount(() => {
    groupData({ type: groupType.value }).then((res: any) => {
        groupOptions.value = res.data;
    });
});
watch(
    () => formData.value.content,
    (newValue, oldValue) => {
        if (newValue.length > 1000) {
            formData.value.content = oldValue;
        }
    },
    { deep: true, immediate: true }
);
</script>

<style lang="scss" scoped>
.verbal_trick {
    display: flex;
    box-sizing: border-box;
    height: 100%;
}

.scrollbar_left {
    flex: 1;
}

.border_lin {
    width: 1px;
    background-color: #eaeaea;
}

.form {
    padding: 24px;
}

.pop_select_box {
    height: 84px;

    .upload_btn {
        margin-top: 8px;
    }

    .upload_pop {
        background: #fff;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .item_pop {
            width: 60px;
            height: 62px;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
            cursor: pointer;

            .item_pop_icon {
                width: 40px;
            }

            .item_pop_name {
                font-size: 14px;
                margin-top: 2px;
                font-family: PingFangSC-Regular, 'PingFang SC';
                font-weight: 400;
                color: #1a1918;
            }
        }
    }
}

.btns {
    margin-top: 11px;
    text-align: center;
}

:deep(.el-textarea__inner) {
    color: #33302d;
}

.content-left {
    flex: 1;
    padding-right: 48px;
}

.content-right {
    padding: 24px 48px;

    .phone-title {
        text-align: center;
        margin-bottom: 20px;
    }
}
</style>
